using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.IO;

namespace ThaiRomanizationHelper
{
    public partial class CopyToChulaThaiRom : Form
    {
        String file = @"C:\temp\th.txt";

        public CopyToChulaThaiRom()
        {
            InitializeComponent();
        }

        private void bnPaste_Click(object sender, EventArgs e)
        {
            // Copy
            String text = Clipboard.GetText(TextDataFormat.UnicodeText);
            text = text.Trim();
            tbText.Text = text;
            

            // Select the app
            Process[] ps = Process.GetProcessesByName("TRoman");
            if (ps == null || ps.Length < 1) 
            { 
                MessageBox.Show("No Thai Romanization process started.");
                return;
            }

            IntPtr windowHandle = ps[0].MainWindowHandle;
            SetForegroundWindow(windowHandle);

            // Hack to send Thai encoded chars as fake ANSI
            // (don't ask why, the app is just crappy)
            Encoding tis620 = Encoding.GetEncoding("TIS-620");

            /*
            if (cbSaveToFile.Enabled)
            {
                File.WriteAllText(file, text, tis620);
                return;
            }
            */

            byte[] bytes = tis620.GetBytes(text);

            StringBuilder sb = new StringBuilder();
            foreach (byte b in bytes) { sb.Append((char)b); }

            Clipboard.SetText(sb.ToString(), TextDataFormat.Text);
            SendKeys.SendWait("^V");

            Clipboard.SetText(text, TextDataFormat.UnicodeText);

        }



        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);


        private void bDecodeThai_Click(object sender, EventArgs e)
        {
            Encoding tis620 = Encoding.GetEncoding("TIS-620");
            String foo = File.ReadAllText(@"C:\temp\th.txt.rom", tis620);
            tbText.Text = foo;
        }
    }
}